package test;

import java.io.*;
import java.net.*;
import pear.gui.table.FilePart;
import pear.other.Helper;

/**
 *
 * @author Dingo
 */
public class Sender {

    public void metoda() throws MalformedURLException, IOException {
        HttpURLConnection con = (HttpURLConnection) new URL("http://pctr.pl/").openConnection();
        con.setDoOutput(true);
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401");
        //con.setRequestMethod("POST");
        //OutputStream os = httpUrlConnection.getOutputStream();
        //OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

        String data = "MAX_FILE_SIZE=16777216"
                + "&send=" + URLEncoder.encode("Wrzuć plik", "UTF-8")
                + "&file=";
        //writer.write(data);
        // writer.flush();
        OutputStream os = con.getOutputStream();
        File file = new File("D:\\Inne\\eksperyment\\pear\\test2.png");
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));

        os.write(data.getBytes("UTF-8"));
        os.flush();
        int byteTrasferred = 0;
        for (int i = 0; i < file.length(); i++) {
            os.write(fis.read());
            byteTrasferred = i + 1;
        }
        os.flush();
        os.close();
        InputStream is = con.getInputStream();
        System.out.println("Przetransportowano:" + byteTrasferred);
        System.out.println(Helper.inputStreamToString(is));
    }

    public static String send(FilePart filePart, File file, String url) throws MalformedURLException, IOException {
        double len = file.length();//tu są Bajty
        double size = len / 1024;//tu są kB!
        filePart.setSize(size);
        filePart.setReminingSize(size);
        filePart.setProgress(0);

        int bufferSize = 102400;


        String boundary = Long.toHexString(System.currentTimeMillis());

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setChunkedStreamingMode(bufferSize);
        PrintWriter writer = null;
        String charset = "UTF-8";
        String CRLF = "\r\n";
        try {
            OutputStream output = connection.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

            // Send normal param.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"MAX_FILE_SIZE\"").append(CRLF);
            writer.append(CRLF);
            writer.append("16777216").append(CRLF).flush();

            // Send binary file.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + "test2.png" + "\"").append(CRLF);
            writer.append("Content-Type: image/png").append(CRLF);
            writer.append(CRLF).flush();
            InputStream input = null;

            Long startTime = System.currentTimeMillis();
            Long deltaTime;

            try {
                input = new FileInputStream(file);
                byte[] buffer = new byte[bufferSize];//tu jest 100kB
                for (int length = 0, i = 0; (length = input.read(buffer)) > 0; i++) {
                    filePart.setReminingSize(size);
                    filePart.setProgress((int) ((filePart.getSize() - size) / filePart.getSize() * 100));
                    System.out.println("Pozostało: " + size);
                    System.out.println("Process: " + filePart.getProgress());


                    output.write(buffer, 0, length);
                    size -= 100;

                    if (i % 10 == 9) {
                        //100*10kB * 1s / np. 0.29ms
                        deltaTime = System.currentTimeMillis() - startTime;
                        double kBps = 1000 / (double)(deltaTime) * 1000;
                        if (deltaTime != 0) {
                            System.out.println("Prędkość: " + kBps + " kBps");
                        } else {
                            System.out.println("Prędkość: 0 kBps ;p");
                        }
                        startTime = System.currentTimeMillis();
                    }
                }
                output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException logOrIgnore) {
                    }
                }
            }
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of binary boundary.


            //dodaj zwykle
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"send\"").append(CRLF);
            writer.append(CRLF);
            writer.append("Wrzuć plik").append(CRLF).flush();

            // End of multipart/form-data.
            writer.append("--" + boundary + "--").append(CRLF);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        System.out.println("yu");
        InputStream is = connection.getInputStream();
        filePart.setProgress(100);
        return Helper.inputStreamToString(is);
    }
    
    public void getDownloadLink() {
        
    }

    public void metoda2() throws MalformedURLException, IOException {

        long transferedBits = 0;

        String boundary = Long.toHexString(System.currentTimeMillis());

        URLConnection connection = new URL("http://pctr.pl/").openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        PrintWriter writer = null;
        String charset = "UTF-8";
        String CRLF = "\r\n";
        try {
            OutputStream output = connection.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

            // Send normal param.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"MAX_FILE_SIZE\"").append(CRLF);
            writer.append(CRLF);
            writer.append("16777216").append(CRLF).flush();


            // Send binary file.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + "test2.png" + "\"").append(CRLF);
            writer.append("Content-Type: image/png").append(CRLF);
            writer.append(CRLF).flush();
            InputStream input = null;
            try {
                File file = new File("D:\\Inne\\eksperyment\\pear\\test2.png");
                input = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                for (int length = 0; (length = input.read(buffer)) > 0;) {
                    transferedBits += length;
                    output.write(buffer, 0, length);
                }
                output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException logOrIgnore) {
                    }
                }
            }
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of binary boundary.


            //dodaj zwykle
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"send\"").append(CRLF);
            writer.append(CRLF);
            writer.append("Wrzuć plik").append(CRLF).flush();

            // End of multipart/form-data.
            writer.append("--" + boundary + "--").append(CRLF);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        InputStream is = connection.getInputStream();
        System.out.println("Przetransportowano:" + transferedBits);
        System.out.println(Helper.inputStreamToString(is));

    }
}